package com.xiaoniu.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoniu.forum.dao.MemberDao;
import com.xiaoniu.forum.entity.MemberEntity;
import com.xiaoniu.forum.form.PhoneLoginForm;
import com.xiaoniu.forum.form.UsernamePasswordLoginForm;
import com.xiaoniu.forum.renren.common.exception.RRException;
import com.xiaoniu.forum.renren.common.validator.Assert;
import com.xiaoniu.forum.service.AppLoginService;
import com.xiaoniu.forum.service.MemberService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AppLoginServiceImpl implements AppLoginService {

    @Autowired
    private MemberDao memberDao;

    @Override
    public String phoneLogin(PhoneLoginForm form) {
        MemberEntity member = queryByKeyValue("phone",form.getMobile());
        Assert.isNull(member, "手机号或密码错误");
        //密码错误
        if(!member.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))){
            throw new RRException("手机号或密码错误");
        }

        return member.getId();
    }

    @Override
    public String usernamePasswordLogin(UsernamePasswordLoginForm form) {
        MemberEntity member = queryByKeyValue("username",form.getUsername());
        Assert.isNull(member, "用户名或密码错误");

        //密码错误
        if(!member.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))){
            throw new RRException("用户名或密码错误");
        }

        return member.getId();
    }

    private MemberEntity queryByKeyValue(String key,Object value) {
        return memberDao.selectOne(new QueryWrapper<MemberEntity>().eq(key, value));
    }
}
